package com.sso.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;

public class PropertiesParse {

	private String propFile;
	
	public String getPropFile() {
		return propFile;
	}


	public void setPropFile(String propFile) {
		this.propFile = propFile;
	}

	public Properties parsePropFile(){
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			if(getPropFile() != null) {
				File file = new ClassPathResource(getPropFile()).getFile();
				fis = new FileInputStream(file);
				prop.load(fis);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return prop;
	}

	public static Object loadAtrrbuteFromPropertiesWithoutNullAndEmpty(Object toObj, Properties prop) {
		if(prop == null || prop.isEmpty()) {
			return toObj;
		}
		Object[] propKey = (Object[])prop.keySet().toArray();
		for (int i = 0; i < propKey.length; i++) {
			if (BeanTool.canAccess(toObj, propKey[i].toString())) {
				try {
					Object value = prop.getProperty(propKey[i].toString());
					if (value != null && value.toString().trim().length() > 0)
						BeanTool.setAttributeByString(toObj, propKey[i].toString(), (String) value);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		return toObj;
	}
	
	public static Properties loadToMapWithOutEmpty(Object obj) {
		Properties map = new Properties();
		String[] names = new String[0];
		try {
			names = BeanTool.getAtrributeNames(obj);
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}
		for (int i = 0; i < names.length; i++) {
			if (BeanTool.canAccess(obj, names[i])) {
				try {
					Object value = BeanTool.getAttributeValue(obj, names[i]);
					if (value != null && value.toString().trim().length() > 0)
						map.put(names[i], value);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		return map;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PropertiesParse propParse = new PropertiesParse();
		propParse.setPropFile("ajaxData.ver");
		Properties prop = propParse.parsePropFile();
		System.out.println(prop.get("key"));
	}

}
